#include <stdio.h>
#include <conio.h>
#include <exception>
#include <vector>
#include <winsock2.h>
#include <ws2tcpip.h>

using namespace std;

#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "Advapi32.lib")

typedef unsigned int uint;
#define LOGF			printf
#define LOG_VALUE(val)	log_value(#val, val)
#define LOG_INIT(s)		printf("INIT : %s\r\n", s)
#define LOG_SHUTDOWN(s)	printf("SHUTDOWN : %s\r\n", s)

inline void log_value(const char *name, int   val)			{ LOGF("%-30s = %d\r\n", name, val); }
inline void log_value(const char *name, float val)			{ LOGF("%-30s = %f\r\n", name, val); }
inline void log_value(const char *name, const char *val)	{ LOGF("%-30s = %s\r\n", name, val); }


#include "..\udp_sv\net_helper.h"
#include "..\udp_sv\net_shared.h"

struct client_s {
		SOCKET		socket;
		sockaddr_in	addr;
		int			time;
	};

class	EServer {
	public:
				EServer				( unsigned int port );
				~EServer			( void );
		void	WaitForConnection	( void );
		void	PerformNetIO		( void );
		void	Frame				( void );
	protected:
		SOCKET		sock_listen;
		sockaddr_in	addr_listen;
		uint		port_listen;
		
		vector<client_s>	clients;
	};


EServer::EServer(unsigned int port)
{
	unsigned long enable = 1;
	int one = 1;

	WSAData	wsa_data;
	memset(&wsa_data, 0, sizeof(wsa_data));
	WSAStartup(MAKEWORD(2, 2), &wsa_data);
	
	addr_listen.sin_family		= AF_INET;
	addr_listen.sin_port		= htons(port_listen);
	addr_listen.sin_addr.s_addr = htonl(INADDR_ANY);
	
    struct addrinfo *result = NULL;
    struct addrinfo	hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the server address and port
    CHECK_WSA( getaddrinfo(NULL, "12345", &hints, &result) );

	sock_listen	=	socket(result->ai_family, result->ai_socktype, result->ai_protocol);
	CHECK_SOCKET(sock_listen);

	//	TODO : make function for socket creation :
	CHECK_WSA( bind(sock_listen, result->ai_addr, (int)result->ai_addrlen) );
	CHECK_WSA( ioctlsocket( sock_listen, FIONBIO, &enable ) );
	// TCP - no broadcast : CHECK_WSA( setsockopt( sock_listen, SOL_SOCKET, SO_BROADCAST, (char*)&one, sizeof(one)) );
	
	freeaddrinfo(result);
	
	CHECK_WSA( listen( sock_listen, SOMAXCONN) );
}	
	

void EServer::Frame(void)
{
	Sleep(1);
	SOCKET		sock_client;
	sockaddr_in addr_client;
	int			addr_client_size = sizeof(addr_client);
	
	sock_client	=	accept(sock_listen, (sockaddr*)&addr_client, &addr_client_size);

	//
	//	Accept clients :
	//	
	if (sock_client!=INVALID_SOCKET) {
		
		client_s cl;
		cl.socket	= sock_client;
		cl.addr		= addr_client;
		cl.time		= 100;
		
		clients.push_back( cl );
		
		LOGF("client connected\r\n");
		LOGF("  port : %d\r\n", cl.addr.sin_port);
		LOGF("  addr : %s\r\n", inet_ntoa(cl.addr.sin_addr));
		
	} else {
		if (WSAGetLastError()!=WSAEWOULDBLOCK) {
			throw exception(NET_ErrorString());
		}
	}
	

	//
	//	Perform session with each client :
	//
	vector<client_s>::iterator cl;
	int i = 0;
	
	for (cl=clients.begin(); cl!=clients.end(); i++) {
	
		if (cl->time<=0) {	
			cl->time = rand()%1000 + 50;
			int r = send(cl->socket, "echo!!!", 8, 0);
			LOGF("%d bytes sent to client #%d\r\n", r, i);
		}
		cl->time--;

		try {
		
			ENetPacket_s packet;
			packet.Fill(0);
			int r = recv( cl->socket, (char*)&packet, MAX_PACKET_SIZE, 0);
			
			if (r==SOCKET_ERROR) {
				if (WSAGetLastError()!=WSAEWOULDBLOCK) {
					throw exception(NET_ErrorString());
				}
			} else {
				LOGF("client : #%d bytes\r\n", i);
				LOGF("  port : %d\r\n", cl->addr.sin_port);
				LOGF("  addr : %s\r\n", inet_ntoa(cl->addr.sin_addr));
				LOGF("  read : %d bytes\r\n", r);
				LOGF("  data : %s\r\n", packet.data);
			}
			
		} catch (exception &e) {
			LOGF("client #%d\r\n", i);
			LOGF("  port : %d\r\n", cl->addr.sin_port);
			LOGF("  addr : %s\r\n", inet_ntoa(cl->addr.sin_addr));
			LOGF("%s\r\n", e.what());
			
			cl = clients.erase(cl);
			continue;
		}	
		cl++;
	}
}	
	
	
EServer::~EServer(void)
{
	WSACleanup();
}	
	

/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/

int __cdecl main(void) 
{
	try {
		EServer sv(12345);
		
		LOGF("listening...\r\n");

		while (true) {		
			sv.Frame();
		}

	} catch (exception &e) {
		LOGF("Error : %s\r\n", e.what());
	}	
	getch();	//*/
#define DEFAULT_BUFLEN	1024
#define DEFAULT_PORT	"12345"

#if 0
    WSADATA wsaData;
    SOCKET ListenSocket = INVALID_SOCKET,
           ClientSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL;
    struct addrinfo	hints;
    char recvbuf[DEFAULT_BUFLEN];
    int iResult, iSendResult;
    int recvbuflen = DEFAULT_BUFLEN;
    

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", iResult);
        return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Create a SOCKET for connecting to server
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("socket failed: %ld\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // Setup the TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
        printf("listen failed: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // No longer need server socket
    closesocket(ListenSocket);

    // Receive until the peer shuts down the connection
    do {

        iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
        if (iResult > 0) {
            printf("Bytes received: %d\n", iResult);

        // Echo the buffer back to the sender
            iSendResult = send( ClientSocket, recvbuf, iResult, 0 );
            if (iSendResult == SOCKET_ERROR) {
                printf("send failed: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }
            printf("Bytes sent: %d\n", iSendResult);
        }
        else if (iResult == 0)
            printf("Connection closing...\n");
        else  {
            printf("recv failed: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }

    } while (iResult > 0);

    // shutdown the connection since we're done
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

    return 0;
#endif    
}
